package com.catmiw.wyz;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;

import com.catmiw.wyz.util.ExcelUtils;

/**
 * 王奕卓英语训练类
 * 
 * @author wl
 * 
 */
public class EnglishTrainning {
	public static String XLSFILENAME = "D:/王奕卓的教育/基础学习训练/王奕卓英语单词短语句型.xls";
	public static Random RAND = new Random();
	public static String[] DATEFORMAT = { "yyyyMMdd" };

	public static void print(List list) {
		int count = 0;
		for (Object o : list) {
			System.out.println(o);
		}
	}

	// 错误测试周期
	public static int ERRORTESTPERIOD = 60;
	public static double ERRORRATIOPOW =2.0;
	public static double TESTTIMESPOW = 0.2;

	public static List<WordInfo> createWordTestList(int count, int unit,
			String kind,String sdate) {
		List<WordInfo> words = loadWordList(kind);
		List<WordInfo> testwords = new ArrayList<WordInfo>();
		// 优先测试
		List<WordInfo> firstwords = new ArrayList<WordInfo>();
		for (WordInfo word : words) {
			// 上次测试没通过的单词必测
			if ( word.getLasttestdate() > word.getLastpassdate() && count > testwords.size()) {
				testwords.add(word);
			} else {
				// 超过测试周期的优先测试
				Date date = null;
				try {
					date = DateUtils.parseDate("" + word.getLasttestdate(),
							DATEFORMAT);
					int adddays=0;
					if (word.getTesttimes()==0){
						adddays=ERRORTESTPERIOD*3/4;
					} else {
						adddays=(int)(ERRORTESTPERIOD*Math.pow(word.getPasstimes()/word.getTesttimes(),
								ERRORRATIOPOW)*Math.pow(word.getTesttimes(),TESTTIMESPOW));
					}
					date = DateUtils.addDays(date,adddays);
					if (((DateUtils.parseDate(sdate,DATEFORMAT)).compareTo(date) > 0)
							&& word.getUnit() <= unit) {
						firstwords.add(word);
					}
				} catch (ParseException e1) {
					e1.printStackTrace();
				}

			}
		}
		
		// 先从优先测试里面加
		System.out.println(firstwords.size());
		if (firstwords.size() <= count - testwords.size()) {
			testwords.addAll(firstwords);
		} else {
			while (testwords.size() < count) {
				int rand = RAND.nextInt(firstwords.size());
				testwords.add(firstwords.get(rand));
				firstwords.remove(rand);
			}
		}

		while (testwords.size() < count) {
			int rand = RAND.nextInt(words.size());
			WordInfo word2 = words.get(rand);
			if (!testwords.contains(word2) && word2.getUnit() <= unit) {
				testwords.add(word2);
			}
		}

		for (WordInfo wi : testwords) {
			wi.setRandnum(RAND.nextInt(2000));
		}
		Collections.sort(testwords, new Comparator<WordInfo>() {
			public int compare(WordInfo w1, WordInfo w2) {
				return w1.getRandnum() - w2.getRandnum();
			}
		});

		//print(testwords);

		return testwords;
	}

	public static WordInfo getWordFromRow(Row row) {
		WordInfo word = new WordInfo();
		word.setNo(new Double(row.getCell(0).getNumericCellValue()).intValue());
		word.setUnit(new Double(row.getCell(1).getNumericCellValue())
				.intValue());
		word.setWord(row.getCell(2).getStringCellValue());
		word.setLastpassdate(new Double(row.getCell(4) == null ? 20100101 : row
				.getCell(4).getNumericCellValue()).intValue());
		word.setLasttestdate(new Double(row.getCell(3) == null ? 20100101 : row
				.getCell(3).getNumericCellValue()).intValue());
		word.setPasstimes(new Double(row.getCell(5) == null ? 0 : row
				.getCell(5).getNumericCellValue()).intValue());
		word.setTesttimes(new Double(row.getCell(6) == null ? 0 : row
				.getCell(6).getNumericCellValue()).intValue());
		return word;
	}

	public static List<WordInfo> loadWordList(String kind) {
		InputStream inp = null;
		List<WordInfo> words = new ArrayList<WordInfo>();

		try {
			inp = new FileInputStream(XLSFILENAME);
			HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
			Sheet sheet = wb.getSheet(kind);
			int count = -1;
			for (Row row : sheet) {
				count++;
				if (count == 0)
					continue;
				WordInfo word = getWordFromRow(row);
				for (WordInfo wi : words) {
					if (wi.getWord().equals(word.getWord())) {
						throw new RuntimeException("发现重复的单词：" + wi.getWord());
					}
				}
				words.add(word);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inp != null) {
				try {
					inp.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return words;
	}

	public static Workbook getWorkbook() {
		return ExcelUtils.getWorkbook(XLSFILENAME);
	}

	public static void createTestPaper(int unit,int wordcount, int phrasecount,
			int grammarcount) {
		String sheetname = DateFormatUtils.format(new Date(), "yyyyMMdd");
		createTestPaper(unit,wordcount, phrasecount, grammarcount, sheetname);
	}

	/**
	 * 产生测试卷
	 * 
	 * @param wordcount
	 * @param phrasecount
	 * @param grammarcount
	 * @param sheetname
	 */
	public static void createTestPaper(int unit,int wordcount, int phrasecount,
			int grammarcount, String sheetname) {
		int rowcount = 0;

		List<WordInfo> words = createWordTestList(wordcount, unit, "单词",sheetname);
		List<WordInfo> phrases = createWordTestList(phrasecount, unit, "短语",sheetname);
		List<WordInfo> grammars = createWordTestList(grammarcount, unit, "句型",sheetname);

		Workbook wb = getWorkbook();
		CellStyle style = wb.createCellStyle();
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setBorderTop(CellStyle.BORDER_THIN);

		CellStyle style2 = wb.createCellStyle();
		style2.cloneStyleFrom(style);
		style2.setAlignment(CellStyle.ALIGN_CENTER);
		style2.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

		Sheet sheet = wb.getSheet(sheetname);

		if (sheet == null) {
			sheet = wb.createSheet(sheetname);
			wb.setSheetOrder(sheetname, 6);
		}
		wb.setActiveSheet(wb.getSheetIndex(sheet));
		sheet.setColumnWidth(0, 10000);
		sheet.setColumnWidth(1, 1500);
		sheet.setColumnWidth(2, 10000);
		sheet.setColumnWidth(3, 1500);

		Row row = sheet.createRow(rowcount++);
		row.setHeight((short) (row.getHeight() * 1.5));
		Cell cell = row.createCell(0);
		cell.setCellValue(sheetname + "测试");
		cell.setCellStyle(style2);
		for (int j = 1; j < 4; j++) {
			cell = row.createCell(j);
			cell.setCellStyle(style);
		}
		sheet.addMergedRegion(new CellRangeAddress(rowcount - 1, rowcount - 1,
				0, 3));

		row = sheet.createRow(rowcount++);
		row.setHeight((short) (row.getHeight() * 1.3));
		cell = row.createCell(0);
		cell.setCellValue("     1. 单词");
		cell.setCellStyle(style);
		for (int j = 1; j < 4; j++) {
			cell = row.createCell(j);
			cell.setCellStyle(style);
		}
		sheet.addMergedRegion(new CellRangeAddress(rowcount - 1, rowcount - 1,
				0, 3));

		for (int i = 0; i < wordcount / 2; i++) {
			row = sheet.createRow(rowcount++);
			for (int j = 0; j < 2; j++) {
				WordInfo word = words.get(i * 2 + j);
				cell = row.createCell(j * 2);
				cell.setCellStyle(style);

				cell.setCellValue(word.getWord());
				cell = row.createCell(j * 2 + 1);
				cell.setCellStyle(style);
			}
		}
		row = sheet.createRow(rowcount++);
		row.setHeight((short) (row.getHeight() * 1.3));
		cell = row.createCell(0);
		cell.setCellValue("     2. 短语");
		cell.setCellStyle(style);
		for (int j = 1; j < 4; j++) {
			cell = row.createCell(j);
			cell.setCellStyle(style);
		}
		sheet.addMergedRegion(new CellRangeAddress(rowcount - 1, rowcount - 1,
				0, 3));

		for (int i = 0; i < phrasecount / 2; i++) {
			row = sheet.createRow(rowcount++);
			for (int j = 0; j < 2; j++) {
				WordInfo word = phrases.get(i * 2 + j);
				cell = row.createCell(j * 2);
				cell.setCellStyle(style);

				cell.setCellValue(word.getWord());
				cell = row.createCell(j * 2 + 1);
				cell.setCellStyle(style);
			}
		}
		row = sheet.createRow(rowcount++);
		row.setHeight((short) (row.getHeight() * 1.3));
		cell = row.createCell(0);
		cell.setCellValue("     3. 句型");
		cell.setCellStyle(style);
		for (int j = 1; j < 4; j++) {
			cell = row.createCell(j);
			cell.setCellStyle(style);
		}
		sheet.addMergedRegion(new CellRangeAddress(rowcount - 1, rowcount - 1,
				0, 3));

		for (int i = 0; i < grammarcount; i++) {
			row = sheet.createRow(rowcount++);
			WordInfo word = grammars.get(i);
			cell = row.createCell(0);
			cell.setCellStyle(style);
			cell.setCellValue(word.getWord());

			for (int j = 1; j < 4; j++) {
				cell = row.createCell(j);
				cell.setCellStyle(style);
			}
			sheet.addMergedRegion(new CellRangeAddress(rowcount - 1,
					rowcount - 1, 0, 2));
		}

		ExcelUtils.writeWorkbook(wb,XLSFILENAME);
	}

	public static void writeRow(Row row, WordInfo word) {
		Cell cell = row.getCell(4);
		if (cell == null)
			cell = row.createCell(4);
		cell.setCellValue(word.getLastpassdate());
		cell = row.getCell(3);
		if (cell == null)
			cell = row.createCell(3);
		cell.setCellValue(word.getLasttestdate());
		cell = row.getCell(5);
		if (cell == null)
			cell = row.createCell(5);
		cell.setCellValue(word.getPasstimes());
		cell = row.getCell(6);
		if (cell == null)
			cell = row.createCell(6);
		cell.setCellValue(word.getTesttimes());
	}

	public static void updateDetail(List<WordInfo> words, Workbook wb,
			String sheetname, String testdate) {
		Sheet sheet = wb.getSheet(sheetname);
		int count = -1;
		for (Row row : sheet) {
			count++;
			if (count == 0)
				continue;
			WordInfo word = getWordFromRow(row);
			if (words.indexOf(word) >= 0) {
				WordInfo w1 = words.get(words.indexOf(word));
				if (Integer.parseInt(testdate) != word.getLasttestdate()) {
					word.setLasttestdate(Integer.parseInt(testdate));
					word.setPasstimes(word.getPasstimes() + w1.getPasstimes());
					word.setTesttimes(word.getTesttimes()+1);
					if (w1.getPasstimes() > 0) {
						word.setLastpassdate(Integer.parseInt(testdate));
					}
					writeRow(row, word);
					System.out.println("update:"+word);
				}
			}
		}

	}

	public static void writeResult(int wordcount, int phrasecount,
			int grammarcount, String sheetname) {
		Workbook wb = getWorkbook();
		Sheet sheet = wb.getSheet(sheetname);
		List<WordInfo> words = new ArrayList<WordInfo>();
		List<WordInfo> phrases = new ArrayList<WordInfo>();
		List<WordInfo> grammars = new ArrayList<WordInfo>();

		if (sheet == null) {
			throw new RuntimeException("无法找到SHEET：" + sheetname);
		}
		Row row = null;
		Cell cell1 = null, cell2 = null;
		for (int i = 2; i < wordcount / 2 + 2; i++) {
			row = sheet.getRow(i);
			for (int j = 0; j < 2; j++) {
				cell1 = row.getCell(j * 2);
				cell2 = row.getCell(j * 2 + 1);
				WordInfo word = new WordInfo();
				word.setWord(cell1.getStringCellValue());
				String tf = cell2.getStringCellValue();
				if (tf == null || tf.trim().equals("")) {
					word.setPasstimes(1);
				} else {
					word.setPasstimes(0);
				}
				
				words.add(word);
			}
		}
		for (int i = 3 + wordcount / 2; i < phrasecount / 2 + 3 + wordcount / 2; i++) {
			row = sheet.getRow(i);
			for (int j = 0; j < 2; j++) {
				cell1 = row.getCell(j * 2);
				cell2 = row.getCell(j * 2 + 1);
				WordInfo word = new WordInfo();
				word.setWord(cell1.getStringCellValue());
				String tf = cell2.getStringCellValue();
				if (tf == null || tf.trim().equals("")) {
					word.setPasstimes(1);
				} else {
					word.setPasstimes(0);
				}

				phrases.add(word);
			}
		}
		for (int i = 4 + wordcount / 2 + phrasecount / 2; i < grammarcount + 4
				+ wordcount / 2 + phrasecount / 2; i++) {
			row = sheet.getRow(i);
			cell1 = row.getCell(0);
			cell2 = row.getCell(3);
			WordInfo word = new WordInfo();
			word.setWord(cell1.getStringCellValue());
			String tf = cell2.getStringCellValue();
			if (tf == null || tf.trim().equals("")) {
				word.setPasstimes(1);
			} else {
				word.setPasstimes(0);
			}

			grammars.add(word);
		}
		updateDetail(words, wb, "单词", sheetname);
		updateDetail(phrases, wb, "短语", sheetname);
		updateDetail(grammars, wb, "句型", sheetname);

		ExcelUtils.writeWorkbook(wb,XLSFILENAME);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		createTestPaper(15, 50, 10, 10);
		//writeResult(50, 10, 10, "20120520");
	}

}
